<template>
  <div class="app-layout">
    <!-- 侧边栏 - 在聊天页面和首页都显示 -->
    <ConversationSidebar 
      v-if="showSidebar"
      :active-conversation-id="activeConversationId"
      @conversation-selected="onConversationSelected"
      @new-chat-requested="onNewChatRequested"
      ref="sidebarRef"
    />

    <!-- 主内容区域 -->
    <div class="main-content" :class="{ 'with-sidebar': showSidebar }">
      <!-- 顶部导航栏 -->
      <div class="top-navbar" v-if="showNavbar">
        <div class="navbar-content">
          <div class="navbar-left">
            <!-- 侧边栏切换按钮 -->
            <button 
              v-if="showSidebarToggle"
              class="sidebar-toggle-btn"
              @click="toggleSidebarVisibility"
              :aria-label="sidebarVisible ? '隐藏侧边栏' : '显示侧边栏'"
            >
              <menu-icon v-if="!sidebarVisible" />
              <menu-fold-icon v-else />
            </button>

            <!-- Logo -->
            <div class="logo-container" @click="goToHome">
              <div class="logo">E</div>
              <span class="logo-text">EchoPlay</span>
            </div>
          </div>

          <div class="navbar-right">
            <!-- 用户信息 -->
            <div class="user-info">
              <t-dropdown trigger="click" :options="userMenuOptions" @click="handleUserMenuClick">
                <div class="user-avatar">
                  <t-avatar size="32px" :image="userStore.userAvatarUrl">
                    {{ userStore.avatarFallback }}
                  </t-avatar>
                  <span class="username">{{ userStore.displayName }}</span>
                  <chevron-down-icon size="16" />
                </div>
              </t-dropdown>
            </div>
          </div>
        </div>
      </div>

      <!-- 页面内容 -->
      <div class="page-content">
        <slot />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useUserStore } from '@/stores/user';
import ConversationSidebar from '/src/components/ConversationSidebar.vue';
import { 
  MenuIcon, 
  MenuFoldIcon, 
  ChevronDownIcon 
} from 'tdesign-icons-vue-next';

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();

// 侧边栏组件引用
const sidebarRef = ref();
const sidebarVisible = ref(true);

// 计算属性
const showSidebar = computed(() => {
  // 只在聊天页面显示侧边栏
  return route.name === 'Chat' && sidebarVisible.value;
});

const showNavbar = computed(() => {
  // 在所有需要导航栏的页面显示
  return ['Home', 'Chat'].includes(route.name as string);
});

const showSidebarToggle = computed(() => {
  // 只在Chat页面显示侧边栏切换按钮
  return route.name === 'Chat';
});

const activeConversationId = computed(() => {
  return route.params.id as string;
});

// 用户菜单选项
const userMenuOptions = [
  { content: '个人设置', value: 'profile' },
  { content: '主题设置', value: 'theme' },
  { content: '退出登录', value: 'logout' }
];

// 方法
const toggleSidebarVisibility = () => {
  sidebarVisible.value = !sidebarVisible.value;
  // 保存状态到本地存储
  localStorage.setItem('sidebar-visible', String(sidebarVisible.value));
};

const onConversationSelected = (conversation: any) => {
  // 对话选择处理逻辑，跳转到聊天页面
  console.log('选中对话:', conversation);
  router.push(`/chat/${conversation.id}`);
};

const onNewChatRequested = () => {
  // 新建对话处理逻辑
  console.log('请求新建对话');
  router.push('/home');
};

const goToHome = () => {
  router.push('/home');
};

const handleUserMenuClick = (data: { value: string }) => {
  switch (data.value) {
    case 'profile':
      // 跳转到个人设置页面
      break;
    case 'theme':
      // 打开主题设置
      break;
    case 'logout':
      userStore.clearUserInfo();
      router.push('/login');
      break;
  }
};

// 监听路由变化，刷新对话列表
watch(() => route.name, (newName) => {
  if (['Chat', 'Home'].includes(newName as string) && sidebarRef.value) {
    // 当进入聊天页面或首页时，刷新对话列表
    sidebarRef.value.loadConversations();
  }
});

// 初始化侧边栏可见性状态
const initSidebarVisibility = () => {
  const stored = localStorage.getItem('sidebar-visible');
  if (stored !== null) {
    sidebarVisible.value = stored === 'true';
  }
};

// 组件挂载时初始化
onMounted(() => {
  initSidebarVisibility();
  // 恢复用户信息（如果页面刷新）
  userStore.restoreUserInfo();
});
</script>

<style scoped>
.app-layout {
  display: flex;
  min-height: 100vh;
  background: #0b0b0b;
  color: #fff;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-width: 0;
  transition: all 0.3s ease;
  min-height: 100vh;
}

.main-content.with-sidebar {
  /* 当有侧边栏时的样式调整 */
}

/* 顶部导航栏 */
.top-navbar {
  height: 64px;
  background: rgba(20, 20, 20, 0.95);
  backdrop-filter: blur(20px);
  border-bottom: 1px solid rgba(124,77,255,0.15);
  display: flex;
  align-items: center;
  padding: 0 24px;
  position: relative;
  z-index: 50;
}

.navbar-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  max-width: 1400px;
  margin: 0 auto;
}

.navbar-left,
.navbar-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.sidebar-toggle-btn {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  background: rgba(124,77,255,0.1);
  border: 1px solid rgba(124,77,255,0.2);
  color: #7c4dff;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.sidebar-toggle-btn:hover {
  background: rgba(124,77,255,0.2);
  transform: scale(1.05);
}

.logo-container {
  display: flex;
  align-items: center;
  gap: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.logo-container:hover {
  transform: translateY(-1px);
}

.logo {
  width: 40px;
  height: 40px;
  border-radius: 10px;
  background: linear-gradient(135deg, #7c4dff, #a78bfa);
  display: flex;
  align-items: center;
  justify-content: center;
  color: #0b0b0b;
  font-weight: 900;
  font-size: 20px;
  box-shadow: 0 4px 16px rgba(124,77,255,0.3);
}

.logo-text {
  font-size: 20px;
  font-weight: 700;
  background: linear-gradient(90deg, #c7b8ff, #7c4dff);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
}

.user-info {
  position: relative;
}

.user-avatar {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  border-radius: 12px;
  background: rgba(124,77,255,0.1);
  border: 1px solid rgba(124,77,255,0.2);
  cursor: pointer;
  transition: all 0.3s ease;
}

.user-avatar:hover {
  background: rgba(124,77,255,0.2);
  transform: translateY(-1px);
}

.username {
  font-size: 14px;
  font-weight: 500;
  color: #fff;
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 页面内容 */
.page-content {
  flex: 1;
  position: relative;
  /* Chat页面自己控制滚动，避免双重滚动条 */
  overflow: hidden;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .top-navbar {
    padding: 0 16px;
  }
  
  .navbar-left,
  .navbar-right {
    gap: 12px;
  }
  
  .logo-text {
    display: none;
  }
  
  .username {
    display: none;
  }
}

@media (max-width: 480px) {
  .top-navbar {
    height: 56px;
    padding: 0 12px;
  }
  
  .logo {
    width: 36px;
    height: 36px;
    font-size: 18px;
  }
  
  .navbar-left,
  .navbar-right {
    gap: 8px;
  }
}
</style>